<?php

class Controller_Commerce extends Controller_TemplateNew
{
    public $quantity;
    
	public function before()
	{
		parent::before();
		$this->db = Database::instance();
		$this->model = Model::factory('cart');
                $this->quantity = array();
                $this->section = 'Custom Signs - ';

            $this->_section = 'catalog';

            $this->template->description = $this->settings['description'];
            $this->template->keywords = $this->settings['keywords'];
            $this->template->linkSettings = $this->settings;

            $this->template->header->active='custom';
            $this->template->content = new View('custom/index');
            $this->template->content->downblock = new View('index/downblock');
            $this->template->content->downblock->formIdea = $this->formIdea;
            $this->midle = new View('index/midle');
            
            
            $bottomBlockCategory = $this->mod->getCategoryByAlias('images-79','images');
            $formConfig = $this->mod->getItemByAlias('9','images');
            $this->template->content->downblock->showForm = ($formConfig['checkbox3']==1) ? true : false;
            $bottomBlockItems = $this->mod->getCategoryItems($bottomBlockCategory['id'],'images','position');
            $tempImg = $this->mod->getImagesByItem('images','position');
            $tempAtt = $this->mod->getAttachmentsByItem('images');
            foreach ($tempImg as $v) {
            $bottomBlockItems[$v[0]['itemId']]['box4'] = $this->mod->imagePath($v[0],'box4');
            }
            foreach ($tempAtt as $v) {
            $bottomBlockItems[$v[0]['itemId']]['attacment'] = $this->mod->attachmentPath($v[0]);
            }
            $this->template->content->downblock->items = $bottomBlockItems;
            
            
            //down Block
            $allImages = $this->mod->getImagesByItem('index');
            $bottomBlock = $this->mod->getItem(95, 'index');
            $this->template->content->downblock->formIdea = $this->formIdea;
            $this->template->content->downblock->bottomBlock = $bottomBlock;
            if (isset($allImages[$bottomBlock['id']])) {
                foreach ($allImages[$bottomBlock['id']] as $key=>$value) {
                    $allImages[$bottomBlock['id']][$key]['imgPath'] = $this->mod->imagePath($value,'box4');
                }
            }
            if (isset($allImages)) {
                $this->template->content->downblock->allImages = $allImages;
            }
            //End down block
            //midle Block
            $midle = $this->mod->getItem(202, 'index');
            if (isset($allImages[$midle['id']])) {
                foreach ($allImages[$midle['id']] as $key=>$value) {
                    $temp[$key] = $this->mod->imagePath($value,'box5');
                }
            }
            $this->midle->images = $temp;
            //
            
            
            $signsList = $this->mod->getCategories($this->_section, 'position');
            $this->template->content->signList = $signsList;
            $this->template->title = $this->section.$this->settings['title'];
            $this->addScript('/scripts/jquerytools/jquery.uniform.js');
            $this->addScript('/scripts/custom.js');
            $this->addStyle('/styles/jquerytools/uniform.default.css');
            $this->addStyle('/styles/fonts.css');
	}

	public function actionDeleteItem($section, $token)
	{
		session_start();
		if (isset($_SESSION['cart'][$section]) ? count($_SESSION['cart'][$section]) : false) {
			for ($cnt = 0; $cnt < count($_SESSION['cart'][$section]); $cnt++) {
				if ($_SESSION['cart'][$section][$cnt]['token'] == $token) {
					unset($_SESSION['cart'][$section][$cnt]);
					break;
				}
			}
		}
		$this->response->redirect(Request::$controller . 'checkout/');
	}

	public function actionCheckout()
	{
		$this->template->title = 'Checkout';
		$this->addStyle('/styles/autoform.css');
		$orderItems = array();
		$sections = Cart::instance()->sections;
		$items = array();
                if (isset($_SESSION['cart']) ? count($_SESSION['cart']) : false) {
                    foreach ($sections as $key=>$value) {
                        if (isset($_SESSION['cart'][$key])) {
                            foreach ($_SESSION['cart'][$key] as $section => $cartItems) {

                                $quantity = (isset($cartItems['quantity'])) ? $cartItems['quantity'] : 1;
                                $items[] = array_merge(array('section'=>$key,'isCustom'=>$value['isCustom'], 'quantity' => $quantity,
                                            'source' => $sections[$key]['source']), $cartItems);
                            }
                        }
                    }
                }
//echo '<pre>';
//print_r ($cartItems);
//exit;
                if (isset($_POST['cart']) ? count($_POST['cart']) : false) {
			$_SESSION['cart'] = $_POST['cart'];
			$this->response->redirect(Request::$uri);
		}
		foreach ($items as $item) {
//                    print_r ($item);exit;
			try {
                                if ($item['isCustom']) {
                                    $method = 'validateCustomItem';
                                } else {
                                    $method = 'validateItem';
                                }
				$class = new ReflectionClass(ucfirst($item['source']) == 'Directory' ? 'DirectoryClass' : ucfirst($item['source']));
				$controller = $class->newInstance();
				if ($class->getMethod($method)) {
					if (false !== ($result = $controller->$method($item))) {
						$orderItems[] = array_merge(array('source' => $item['source']), $result);
					}
				}
			} catch (ReflectionException $e) {
				continue;
			}
		}
//                echo '<pre>';
//                print_r ($orderItems);
//                exit;
		$isDigital = true;
		if (count($orderItems)) {
                        $payPalForm = $this->payPalForm();
			if (Request::$method == 'POST') {
                            
                                $order = array();
                                $order['items'] = $orderItems;
                                if (isset($_SESSION['cart']['delivery'])) {
                                        $order['delivery'] = $_SESSION['cart']['delivery'];;
                                        $order['deliveryCost'] = $_SESSION['cart']['deliveryCost'];;
                                } else {
                                        $order['delivery'] = 0;
                                        $order['deliveryCost'] = 0;
                                }
                                $order['shipping'] = $_SESSION['cart']['shipping'];
                                $order['billing'] = $_SESSION['cart']['billing'];
                                $order['coupon'] = (isset($_SESSION['cart']['coupons'])) ? $_SESSION['cart']['coupons'] : false;
//                                        echo '<pre>';
//                                        print_r ($order);
//////                                        print_r ($_SESSION);
//                                        exit;
                                if (!isset($_POST['payment'])) {
                                    if ($orderId = Cart::instance()->createOrder($order)) {
                                            foreach ($sections as $key=>$value) {
                                                unset($_SESSION['cart'][$key]);
                                            }
                                            if ($order = $this->model->getOrder($orderId)) {
                                                    $this->response->redirect($order['paypal']);
                                            }
                                    }
				} else {
                                    if ($payPalForm->validate()) {
                                            $values = $payPalForm->getValues();
                                            $values['acct'] = str_ireplace('-', '', $values['acct']);
                                            $values['expDate'] = $values['expMonth'] . $values['expYear'];
                                            $values['paymentAction'] = 'sale';
                                            $values['countryCode']   = 'US';
                                            $values['currencyCode']  = 'USD';
                                            $values['ReturnUrl'] = urlencode(Url::site('/commerce/ipn/'));
                                            $values['CancelUrl'] = urlencode(Url::site('/'));
                                            $values['amt'] = Cart::instance()->getAmount($order['items'], $order['deliveryCost'], $order['coupon']);
                                            $response = Paypal::getInstance()->request('DoDirectPayment', $values);
                                            if (isset($response['ack']) ? (strtolower($response['ack']) == 'success' || strtolower($response['ack']) == 'successwithwarning') : false) {
                                                    foreach ($sections as $key=>$value) {
                                                        unset($_SESSION['cart'][$key]);
                                                    }
                                                    $order['paypalMethod'] = 'DoDirectPayment';
                                                    $order['paypalAck'] = $response['ack'];
                                                    $order['paypalCorrelationId'] = $response['correlationid'];
                                                    $order['paypalTimestamp'] = $response['timestamp'];
                                                    $order['dateTimePaid'] = date('Y-m-d h:i');
                                                    $orderId = Cart::instance()->createOrder($order);
                                                    if ($order = $this->model->getOrder($orderId)) {
                                                            Cart::instance()->setPaid($orderId);
                                                            $this->response->redirect('signs/thank');
                                                    }
                                            } else {
                                                $errors = '';
                                                foreach ($response as $k => $v) {
                                                        if (preg_match_all('/^l_shortmessage(\d+)$/i', $k, $matches, PREG_SET_ORDER)) {
                                                                if ($response['l_shortmessage' . $matches[0][1]] != 'Invalid Parameter') {
                                                                        $errors .= View::factory('payment/error', array('title' => $response['l_shortmessage' . $matches[0][1]], 'message' => $response['l_longmessage' . $matches[0][1]]));
                                                                }
                                                        }
                                                }
                                            }
                                    }
                                }
			}
                        
//                        $this->template->content->items = $orderItems;
//                        $this->template->content->form = $form;
//			$this->template->content = new View('checkout');
//			if (isset($this->settings['delivery'])) {
//				$this->template->content->delivery = $this->settings['delivery'];
                        $this->template->content->activeCategoryId = null;
                        $this->template->content->signsContent = new View('checkout');
                        $this->template->content->signsContent->orderItems = $orderItems;
                        $this->template->content->signsContent->delivery = array('delivery'=>$_SESSION['cart']['delivery'],
                                                                                'deliveryCost'=>$_SESSION['cart']['deliveryCost']);
                        $this->template->content->signsContent->coupons = (isset($_SESSION['cart']['coupons']))?$_SESSION['cart']['coupons'] : false;
                        $this->template->content->signsContent->payPalForm = $payPalForm;
                        $this->template->content->signsContent->midleBlock = $this->midle;
                        if (isset($errors) ? $errors != '' : false) {
                            $this->template->content->signsContent->errors = $errors;
                        }    
		} else {
			$this->template->content = 'Your cart is empty';
		}
            if ($this->neadRenew) {
                $this->template = new View('browser');
            }
                
                
	}

        public function payPalForm () {
            $this->addStyle('/styles/checkoutform.css');
            $form = new Form('payment');
            //$form->template = 'payment/creditcard-form';
//            $form->labelWidth = '150px';
//            $form->fieldset('customer');
//            $form->text('customerCustomer', 'Full name')->rule('required')->attribute('size', 40);
//            $form->text('customerEmail', 'Email')->rule('required')->rule('email')->attribute('size', 40);
//            $form->text('customerAddress', 'Address')->rule('required')->attribute('size', 40);
//            $form->text('customerCity', 'City')->rule('required')->attribute('size', 40);
//            $form->select('customerState', array_merge(array('' => ''), Text::$states), 'State')->rule('required');
//            $form->text('customerZip', 'ZIP-code')->rule('required')->attribute('size', 10)->rule('integer')->rule('minLength', 5);
//            $form->text('customerPhone', 'Phone')->attribute('size', 40);
//            $form->textarea('customerComment', 'Comments')->attribute('cols', 25)->attribute('rows', 10);
            $form->html('creditCardInfo', '', '<strong>Pay with credit card</strong>')->phantom()->bunched();
            $form->text('firstName', 'First name')->rule('required')->attribute('size', 21);
            $form->text('lastName', 'Last name')->rule('required')->attribute('size', 21);
            $form->text('acct', 'Card number')->rule('maxLength', 19)->attribute('size', 21)->rule('required');
            $form->select('creditCardType', array(
                    'visa' => 'VISA',
                    'mastercard' => 'Mastercard',
                    'discover' => 'Discover',
                    'amex' => 'American Express',
            ), 'Card type');
            $form->text('expMonth', 'Expiration month')->rule('minLength', 2)->rule('maxLength', 2)->rule('integer')->attribute('size', 2)->rule('required');
            $form->text('expYear', 'Expiration year')->rule('minLength', 4)->rule('maxLength', 4)->rule('integer')->attribute('size', 4)->rule('required');
            $form->text('cvv2', 'CSC')->attribute('size', 5)->rule('required');
            $form->textarea('street', 'Address')->attribute('cols', 25)->attribute('rows', 3)->rule('required');
            $form->text('city', 'City')->rule('required')->attribute('size', 21);
            $form->select('state', array_merge(array('' => ''), Text::$states), 'State')->rule('required');
            $form->text('zip', 'ZIP code')->attribute('size', 7)->rule('maxLength', 5)->rule('required');
            if ($this->settings['isSandbox']) {
                    $form->elements['firstName']->value = 'Test';
                    $form->elements['lastName']->value = 'User';
                    $form->elements['acct']->value = '4334981618387435';
                    $form->elements['creditCardType']->value = 'visa';
                    $form->elements['expMonth']->value = '01';
                    $form->elements['expYear']->value = '2011';
                    $form->elements['cvv2']->value = '123';
                    $form->elements['street']->value = '';
                    $form->elements['city']->value = 'San Jose';
                    $form->elements['state']->value = 'CA';
                    $form->elements['zip']->value = '95131';
            }
            $form->submit('submit', 'PAY BY CREDIT CARD')->bunched();
            return $form;
        }
        
        
        
        
	public function actionConfirmation($result = 'ok')
	{
		$this->template->title = 'Checkout';
		if ($result == 'ok') {
			$this->template->content = 'Thank you.';
		} elseif ($result == 'cancel') {
			$this->template->content = 'Try next time. Thank you.';
		}
	}
        public function actionUpdatequant ()
        {
            $this->autoRender = false;
            $this->response->setHeader('Content-Type', 'application/json');
            if (Request::$method == 'POST' && Request::$isAjax) {
                $quantity = $_POST['quantity'];
                $itemId = $_POST['itemId'];
                $section = $_POST['section'];
                if ($itemId != '' && $quantity != '' && $section!='') {
                    $_SESSION['cart'][$section][$itemId]['quantity'] = $quantity;
                    $this->response->body = json_encode(array('result'=>true));
                }
            } else {
                $this->response->body = json_encode(array('result'=>false));
            }
        }

	public function actionIpn()
	{
		$this->autoRender = false;
		if ($orderId = $this->validateIpn()) {
			Cart::instance()->setPaid($orderId);
			$this->response->body = 'Payment done';
		} else {
			$this->response->body = 'Payment failed';
		}
	}

	private function log($message, $success = true, $end = false)
	{
		$text = '['.date('m/d/Y g:i A').'] - ' . (($success) ? 'SUCCESS: ' : 'FAILURE: ') . $message . "\n";
		if ($end) {
			$text .= "\n------------------------------------------------------------------\n\n";
		}
		if (!file_exists('_logs/ipn.txt')) {
			file_put_contents('_logs/ipn.txt', '');
		}
		$fp=fopen('_logs/ipn.txt', 'a');
		fwrite($fp, $text);
		fclose($fp);
	}

	private function validateIpn()
	{
		$ipnData = '';
		$ipnResponse = '';
		$this->log('Paypal IPN Intiated by ' . $_SERVER['REMOTE_ADDR'], true);
		if ($this->settings['isSandbox']) {
			$url = 'https://www.sandbox.paypal.com/cgi-bin/webscr';
		} else {
			$url = 'https://www.paypal.com/cgi-bin/webscr';
		}
		$post = '';
		foreach ($_POST as $k => $v) {
			$ipnData[$k] = $v;
			$post .= $k . '=' . urlencode($v) . '&';
		}
		if (isset($ipnData['txn_type']) ? $ipnData['txn_type'] == 'subscr_signup' : false) {
			$this->log('Subscription sign up.', true, true);
			return false;
		}

		$this->log('Post string: ' . $post, true);
		$post .= 'cmd=_notify-validate';

		$itemNumber = (isset($ipnData['item_number']) ? $ipnData['item_number'] : (isset($ipnData['item_number1']) ? $ipnData['item_number1'] : (isset($ipnData['invoice']) ? $ipnData['invoice'] : '')));
		if (!$itemNumber) {
			$this->log('Invalid IPN request.', false, true);
			return false;
		}
		if (!($order = $this->model->getOrderByToken($itemNumber))) {
			$this->log('Invalid order id.', false, true);
			return false;
		}
		$this->log('Order ID: ' . $order['id'], true);
		if ($this->settings['paypalEmail'] != $ipnData['receiver_email']) {
			$this->log('Invalid reciever email.', false, true);
			return false;
		}
		$gross = (isset($ipnData['mc_gross']) ? $ipnData['mc_gross'] : (isset($ipnData['mc_gross_1']) ? $ipnData['mc_gross_1'] : (isset($ipnData['payment_gross']) ? $ipnData['payment_gross'] : 0)));
		if ($order['delivery']) {
			$order['amount'] += $this->settings['delivery'];
		}
		if ($order['amount'] != $gross || 'USD' != $ipnData['mc_currency']) {
			$this->log('Currency: ' . $ipnData['mc_currency'], true);
			$this->log('Invalid amount. It had to be ' . $order['amount'] . ', but got ' . $gross . ' from IPN.', false, true);
			return false;
		}
		$curl = curl_init($url);
		curl_setopt ($curl, CURLOPT_HEADER, 0);
		curl_setopt ($curl, CURLOPT_POST, 1);
		curl_setopt ($curl, CURLOPT_POSTFIELDS, $post);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($curl, CURLOPT_SSL_VERIFYHOST, 1);
		$ipnResponse = curl_exec ($curl);
		curl_close ($curl);
		$this->log('Connection to ' . $url . ' successfuly completed.', true);
		$this->log('IPN response: ' . $ipnResponse, true);
		if (substr_count('VERIFIED', $ipnResponse)) {
			$this->log('IPN successfully verified. Order id is ' . $order['id'] . '.', true, true);
			return $order['id'];
		} else {
			$this->log('IPN validation failed.', false, true);
			return false;
		}
	}

}
